package com.jsy.mini12306.ticketsales.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jsy.mini12306.common.entity.Station;
import com.jsy.mini12306.common.vo.StationVO;
import com.jsy.mini12306.ticketsales.mapper.StationMapper;
import com.jsy.mini12306.ticketsales.service.StationService;
import com.jsy.mini12306.ticketsales.vo.StationsByFirstCharVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
 * 车站（字典表）(Station)表服务实现类
 *
 * @author: SongyangJi
 * @since: 2021-09-01 01:36:35
 * @description:
 */

@Slf4j
@Service("stationService")
public class StationServiceImpl extends ServiceImpl<StationMapper, Station> implements StationService {
    @Resource
    private StationMapper stationMapper;

    @Override
    public List<Station> listStationsByInitialLetter(String c) {
        return stationMapper.selectList(new QueryWrapper<Station>().likeRight("alphabetical", c));
    }

    @Override
    public Station queryByStationName(String stationName) {
        return stationMapper.selectOne(new QueryWrapper<Station>().eq("station_name", stationName));
    }

    @Override
    public List<Station> queryStationsByCity(String cityName) {
        return stationMapper.selectList(new QueryWrapper<Station>().eq("city", cityName));
    }

    @Override
    public List<StationsByFirstCharVO> queryStationsByFirstCharVOs() {
        List<Station> list = this.list();
        // 按首字母排序
        list.sort(Comparator.comparing(Station::getAlphabetical));
        Map<String, StationsByFirstCharVO> map = new HashMap<>();

        list.forEach(station -> {
                    String c = station.getAlphabetical().substring(0, 1);
                    if (!map.containsKey(c)) {
                        StationsByFirstCharVO stationsByFirstCharVO = new StationsByFirstCharVO();
                        // 首字母
                        stationsByFirstCharVO.setTitle(c.toUpperCase());
                        map.put(c,stationsByFirstCharVO);
                    }
                    map.get(c).getList().add(station.getStationVO());
                }
        );
        List<StationsByFirstCharVO> collect = new ArrayList<>(map.values());
        collect.sort(Comparator.comparing(StationsByFirstCharVO::getTitle));
        return collect;
    }
}